package net.ubinow.mflex.events;

import net.ubinow.mflex.util.Constants;



public class EventFactory {
    
    private static final int EVENT_POOL_SIZE = 2;
    
    //<editor-fold defaultstate="collapsed" desc="singleton fields and methods">
    private static EventFactory _instance = null;
    
    public static EventFactory getInstance(){
        if( _instance == null )
            _instance = new EventFactory();
        
        return _instance;
    }
    //</editor-fold>
    
    private Event[] _events = null;
    private int _nxtFreeEvent = 0; 
    
    /** Creates a new instance of EventFactory */
    private EventFactory() {
        
        initEventPool();
    }
    
    private void initEventPool(){
        _events = new Event[EVENT_POOL_SIZE];
        for (int i = 0; i < EVENT_POOL_SIZE; i++) {
            _events[i] = new Event();
        }
    }
    
    synchronized public Event getEvent( int evtType, IEventPublisher source ){
        Event evt = getEvent( evtType );
        evt._publisher = source; 
        
        return evt; 
    }
    
    synchronized public Event getEvent( int evtType ){
        Event evt = null;
        for( int i=_events.length-1; i>=0; i-- ){
            if( !_events[i]._inUse ){
                evt = _events[i];                
            }
        }
        
        if( evt == null ){
            Event[] tmp = new Event[_events.length+Constants.AD_ARRAY_EXPAND_FACTOR]; 
            System.arraycopy( _events, 0, tmp, 0, _events.length );
            int len = tmp.length; 
            for( int i=1; i<=Constants.AD_ARRAY_EXPAND_FACTOR; i++ ){
                if( evt == null ){
                    evt = new Event(); 
                    tmp[len-i] = evt; 
                }
                else{
                    tmp[len-i] = new Event(); 
                }                
            }
            
            _events = tmp;             
        }
        
        evt._inUse = true; 
        evt._type = evtType; 
        
        return evt; 
    }
    
    public void putEvent( Event evt ){
        
    }
}
